# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::BackgroundMigration::FixNamespaceIdsOfVulnerabilityReads, feature_category: :vulnerability_management do # rubocop:disable Layout/LineLength
  let(:namespaces) { table(:namespaces) }
  let(:projects) { table(:projects) }
  let(:users) { table(:users) }
  let(:vulnerability_reads) { table(:vulnerability_reads) }
  let(:vulnerabilities) { table(:vulnerabilities) }
  let(:scanners) { table(:vulnerability_scanners) }

  let(:user) { users.create!(username: 'john_doe', email: 'johndoe@gitlab.com', projects_limit: 1) }
  let(:namespace_1) { namespaces.create!(name: 'Test Namespace', path: 'namespace-path-1') }
  let(:namespace_2) { namespaces.create!(name: 'Test Namespace', path: 'namespace-path-2') }
  let(:project) { projects.create!(name: 'Test', namespace_id: namespace_1.id, project_namespace_id: namespace_1.id) }
  let(:scanner) { scanners.create!(project_id: project.id, external_id: 'foo', name: 'bar') }

  let!(:vulnerability_read_with_correct_namespace) { create_vulnerability_read(namespace_id: namespace_1.id) }
  let!(:vulnerability_read_with_wrong_namespace) { create_vulnerability_read(namespace_id: namespace_2.id) }

  let(:migration_instance) do
    described_class.new(
      start_id: vulnerability_reads.minimum(:vulnerability_id),
      end_id: vulnerability_reads.maximum(:vulnerability_id),
      batch_table: :vulnerability_reads,
      batch_column: :vulnerability_id,
      sub_batch_size: 100,
      pause_ms: 0,
      connection: vulnerability_reads.connection
    )
  end

  subject(:perform_migration) { migration_instance.perform }

  it 'fixes the `namespace_id` data integrity issue' do
    expect { perform_migration }
      .to change { vulnerability_read_with_wrong_namespace.reload.namespace_id }.to(namespace_1.id)
      .and not_change { vulnerability_read_with_correct_namespace.reload.namespace_id }
  end

  def create_vulnerability_read(namespace_id:)
    vulnerability = vulnerabilities.create!(
      project_id: project.id,
      author_id: user.id,
      title: 'Vulnerability 1',
      severity: 1,
      confidence: 1,
      report_type: 1,
      state: 1
    )

    vulnerability_reads.create!(
      vulnerability_id: vulnerability.id,
      namespace_id: namespace_id,
      project_id: project.id,
      scanner_id: scanner.id,
      report_type: 1,
      severity: 1,
      state: 1,
      uuid: SecureRandom.uuid
    )
  end
end
